﻿using Bank_database_system;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static AccountOperations.AccountOperations;
using static LoanOperations.LoanOperations;
using static LoanCalculator.LoanCalculator;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Net;

namespace Bank_database_system.业务部.贷款业务
{
    public partial class 贷款办理b : UserControl
    {
        public event EventHandler ButtonBack;
        private string cardID;
        private string branch_id = "";
        private string staff_id = "";
        public 贷款办理b()
        {
            InitializeComponent();
            cardID = "";
        }

        public void branch_and_staff_get(string branchID, string staffID)
        {
            branch_id = branchID;
            staff_id = staffID;
        }

        // 贷款办理输入密码正确后获取信息
        public void information_Set(string CardID)
        {
            cardID = CardID;
            //身份获取
            DataTable dataTable = CustomerInquiryByCardID(CardID);
            DataRow row = dataTable.Rows[0];

            string identificationNumber = row["IDENTIFICATION_NUMBER"].ToString();
            string name = row["NAME"].ToString();
            string address = row["ADDRESS"].ToString();
            string phoneNumber = row["PHONENUMBER"].ToString();
            string score = BankCardScoreInquiry(CardID);

            textBox5.Text = name;
            textBox1.Text = identificationNumber;
            textBox3.Text = phoneNumber;
            textBox6.Text = address;
            textBox7.Text = score;
        }

        private void LoanAmmountCheck(object sender, KeyPressEventArgs e)
        {
            if (char.IsControl(e.KeyChar))
            {
                return;
            }
            if (char.IsDigit(e.KeyChar) || e.KeyChar == '.')
            {
                // 允许一个小数点
                if (e.KeyChar == '.')
                {
                    if (textBox2.Text.IndexOf('.') > -1)
                    {
                        e.Handled = true;
                    }
                    return;
                }

                // 确保小数点后不超过两位
                if (textBox2.Text.Contains('.'))
                {
                    string[] parts = textBox2.Text.Split('.');
                    if (parts.Length == 2 && parts[1].Length >= 2)
                    {
                        e.Handled = true;
                    }
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        private void LoanTermCheck(object sender, KeyPressEventArgs e)
        {
            if (char.IsControl(e.KeyChar))
            {
                return;
            }
            if (char.IsDigit(e.KeyChar))
            {
                // 确保还款期限不超过两位数
                if (textBox4.Text.Length >= 2)
                {
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        // 贷款办理详细界面的返回
        private void button8_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            ButtonBack?.Invoke(this, EventArgs.Empty);
        }

        private bool CheckBranchBalance(decimal amount)
        {
            string branchCard = GetBranchCardID(branch_id);
            string balance = BankCardBalanceInquiry(branchCard);
            decimal branchBalance = Convert.ToDecimal(balance);
            if (branchBalance < amount)
            {
                MessageBox.Show("贷款数额过大，请更改后重试！");
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool CheckCardScore(decimal inputAmount)
        {
            int score = Convert.ToInt32(BankCardScoreInquiry(cardID));
            if (score < inputAmount)
            {
                MessageBox.Show("信誉分不足，请修改贷款金额后重试！");
                return false;
            }
            return true;
        }

        // 贷款办理详细界面的提交
        private void button9_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "" || textBox6.Text == "")
            {
                MessageBox.Show("贷款信息栏不能为空！");
            }
            else if (comboBox1.SelectedItem == null)
            {
                MessageBox.Show("请选择还款方式！");
            }
            else
            {
                DialogResult result = MessageBox.Show("请再次确认贷款信息无误！", "确认保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    //后端录入
                    int inputTerm = Convert.ToInt32(textBox4.Text);
                    decimal inputAmount = Convert.ToDecimal(textBox2.Text);
                    string branchCard = GetBranchCardID(branch_id);
                    if (!CheckBranchBalance(inputAmount))
                    {
                        return;
                    }

                    RepaymentType chooseRepayment = comboBox1.SelectedItem.ToString() == "等额本金还款"
                                                    ? RepaymentType.EqualPrincipal
                                                    : RepaymentType.EqualPrincipalAndInterest;
                    if (inputTerm > 10)
                    {
                        MessageBox.Show("还款期限超出最大限制（10年），请更改后重试！");
                    }
                    else if (!CheckBranchBalance(inputAmount))
                    {
                        return;
                    }
                    else if (!CheckCardScore(inputAmount))
                    {
                        return;
                    }
                    else
                    {
                        string loanID = LoanProcessing(cardID, branchCard, inputAmount, inputTerm, chooseRepayment);
                        string message1 = "贷款办理，贷款ID为" + loanID;
                        string[] oprates = CreateLoanTransfer(branchCard, cardID, inputAmount, loanID);
                        string message2 = branchCard + " 转账给 " + cardID + " 金额 " + inputAmount;
                        string message3 = cardID + " 收到转账来自 " + branchCard + " 金额 " + inputAmount;
                        if (oprates != null
                            && OperateRecordHandler.InsertOperateRecord(staff_id, "贷款办理", message1, loanID, "", "", "")
                            && OperateRecordHandler.InsertOperateRecord(staff_id, "交易", message2, "", "", "", oprates[0])
                            && OperateRecordHandler.InsertOperateRecord(staff_id, "交易", message3, "", "", "", oprates[1]))
                        {
                            MessageBox.Show("创建成功！");
                            button8_Click(sender, e);
                        }
                        else
                        {
                            MessageBox.Show("操作失败，请稍后重试！");
                            return;
                        }
                    }
                }
            }
        }
        private void textBox4_leave(object sender, EventArgs e)
        {
            if (textBox4.Text != "")
            {
                textBox4.Text = textBox4.Text.TrimStart('0');
                if (textBox4.Text != "")
                {
                    int number = int.Parse(textBox4.Text);
                    if (number > 10)
                    {
                        textBox4.Text = "10";
                    }
                }
            }
        }
        private void label11_Click(object sender, EventArgs e)
        {

        }
    }
}
